<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      :title="ruleForm.id === 0 ? '新增地址' : '编辑地址'"
      width="500"
      :before-close="handleClose"
    >
      <div>
        <el-form
          ref="ruleFormRef"
          style="max-width: 300px"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
          status-icon
        >
          <el-form-item label="地址名称:" prop="name">
            <el-input v-model="ruleForm.name" placeholder="请输入地址名称" clearable />
          </el-form-item>
          <el-form-item label="地址二维码:">
            <vue-qr
              v-if="ruleForm.name"
              id="qrCode"
              :text="ruleForm.name"
              :size="120"
              colorDark="#000"
              colorLight="#ffffff"
              :callback="getImgInfo"
            />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { addressListData } from "@/api/care/address/type";
import vueQr from "vue-qr/src/packages/vue-qr.vue";
import { upload } from "@/api/file/file";
import { addressAdd, addressUpdate } from "@/api/care/address/address";

const dialogVisible = ref(true);

const ruleForm = reactive<addressListData>({
  name: "",
  qrcode: "",
});

const props = withDefaults(defineProps<{ listParams: addressListData }>(), {
  listParams: () => ({
    id: 0,
    name: "",
    qrcode: "",
  }),
});
Object.assign(ruleForm, props.listParams);

// 生成二维码
const base64 = ref("");
const getImgInfo = (data: string) => {
  base64.value = data;
};

// 添加
const submitForm = async () => {
  let dataURL = base64.value; //canvas转成base64
  const uploadRes = await upload(dataURL);
  ruleForm.qrcode = uploadRes.url;
  await addressAdd(ruleForm);
  ElMessage.success("添加成功");
  emit("close");
};

// 修改
const update = async () => {
  let dataURL = base64.value; //canvas转成base64
  const uploadRes = await upload(dataURL);
  ruleForm.qrcode = uploadRes.url;
  await addressUpdate(ruleForm);
  ElMessage.success("修改成功");
  emit("close");
};

const submit = () => {
  ruleFormRef.value?.validate(async (valid) => {
    if (valid) {
      // submitForm()
      ruleForm.id === 0 ? await submitForm() : await update();
    }
  });
};

// 表单校验
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules<addressListData>>({
  name: [{ required: true, message: "请输入地址名称", trigger: "blur" }],
});

const emit = defineEmits(["close"]);
const handleClose = () => {
  emit("close");
};
</script>

<style scoped></style>
